package com.google.code.sip.ucenter.dao.mongo.benchmark;

import java.util.Date;
import java.util.concurrent.CyclicBarrier;

import com.google.code.sip.ucenter.dao.mongo.CreditLogDaoImpl;
import com.google.code.sip.ucenter.model.CreditLog;
import com.google.code.sip.ucenter.model.CreditOperation;

public class WriteBenchmarkThread extends Thread {
	private CreditLogDaoImpl dao = new CreditLogDaoImpl();
	protected int repeats;
	protected int countMax;
	protected CyclicBarrier barrier;
	protected int threadNum;

	public WriteBenchmarkThread(int threadNum, CreditLogDaoImpl dao,
			CyclicBarrier barrier, int repeats, int countMax) {
		this.threadNum = threadNum;
		this.dao = dao;
		this.barrier = barrier;
		this.repeats = repeats;
		this.countMax = countMax;
	}

	@Override
	public void run() {
		int count = 0;
		try {
			barrier.await();
			long beginTime = System.nanoTime();
			for (int repeat = 0; repeat < repeats; repeat++) {
				for (count = 0; count < countMax; count++) {
					CreditLog creditLog = new CreditLog();
					creditLog.setId(String.valueOf(1 * (threadNum + 1)
							* (repeat + 1) + count));
					creditLog.setAmount(10);
					creditLog.setOperation(CreditOperation.TRC);
					creditLog.setCreatedDate(new Date());
					dao.save(creditLog);
					creditLog = null;
				}
			}
			long endTime = System.nanoTime();
			System.out.println("写线程" + threadNum + "执行完毕，耗时："
					+ (endTime - beginTime) + "纳秒("
					+ new Float((endTime - beginTime) / 1000000) + "毫秒)");
			barrier.await();

		} catch (Exception e) {
			System.out.println("已写入" + count + "条记录");
			e.printStackTrace();
		}
	}
}
